using B.S.Requst;
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
using B.S.Domain.InvoiceManagement;
using B.S.Infratrctrue;
using Microsoft.EntityFrameworkCore;

namespace B.S.Data.MES.API.Applications.B.S.KApplications.Command.InvoiceReceiptCommand
{
    /// <summary>
    /// 添加到票命令处理程序
    /// 处理到票信息的新增逻辑
    /// </summary>
    public class AddInvoiceReceiptCommandHandler : IRequestHandler<AddInvoiceReceiptCommand, APIRequst<int>>
    {
        private readonly IBaseRepository<InvoiceReceipt> _invoiceReceiptRepository;
        private readonly IBaseRepository<SalesInvoice> _salesInvoiceRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="invoiceReceiptRepository">到票仓储</param>
        /// <param name="salesInvoiceRepository">销售发票仓储</param>
        public AddInvoiceReceiptCommandHandler(
            IBaseRepository<InvoiceReceipt> invoiceReceiptRepository,
            IBaseRepository<SalesInvoice> salesInvoiceRepository)
        {
            _invoiceReceiptRepository = invoiceReceiptRepository;
            _salesInvoiceRepository = salesInvoiceRepository;
        }

        /// <summary>
        /// 处理添加到票的命令
        /// </summary>
        /// <param name="request">添加到票命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果，返回创建的到票记录ID</returns>
        public async Task<APIRequst<int>> Handle(AddInvoiceReceiptCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证参数
                if (request.InvoiceId <= 0)
                {
                    return new APIRequst<int> { Code = RequstCode.失败, Msg = "发票ID不能为空" };
                }

                if (request.ReceiptAmount <= 0)
                {
                    return new APIRequst<int> { Code = RequstCode.失败, Msg = "到票金额必须大于0" };
                }

                if (request.ReceiptStatus < 0 || request.ReceiptStatus > 2)
                {
                    return new APIRequst<int> { Code = RequstCode.失败, Msg = "到票状态无效" };
                }

                // 检查发票是否存在
                var invoice = await _salesInvoiceRepository.GetAll().FirstOrDefaultAsync(s => s.InvoiceId == request.InvoiceId && !s.isDel);
                if (invoice == null)
                {
                    return new APIRequst<int> { Code = RequstCode.失败, Msg = "发票不存在" };
                }

                // 创建到票记录
                var invoiceReceipt = new InvoiceReceipt
                {
                    InvoiceId = request.InvoiceId,
                    ReceiptDate = request.ReceiptDate,
                    ReceiptAmount = request.ReceiptAmount,
                    ReceiptStatus = request.ReceiptStatus,
                    PaymentMethod = request.PaymentMethod,
                    TransactionNo = request.TransactionNo,
                    Remarks = request.Remarks,
                    CreateName = request.CreateName,
                    CreateTime = DateTime.Now,
                    UpdateName = request.CreateName,
                    UpdateTime = DateTime.Now,
                    isDel = false
                };

                // 保存到数据库
                var result = await _invoiceReceiptRepository.Add(invoiceReceipt);
                if (result <= 0)
                {
                    return new APIRequst<int> { Code = RequstCode.失败, Msg = "添加到票记录失败" };
                }

                return new APIRequst<int>
                {
                    Code = RequstCode.成功,
                    Msg = "添加到票记录成功",
                    Data = invoiceReceipt.ReceiptId
                };
            }
            catch (Exception ex)
            {
                // 记录异常并返回失败结果
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"添加到票记录失败：{ex.Message}"
                };
            }
        }
    }
}